// const CONFIG = require('../config/' + process.env.NODE_ENV + '.env')
var BASE_URL = ''
// http://h5.lingjiamao.cn/\
// http://121.41.164.193
if (process.env.NODE_ENV == 'development') {
	BASE_URL = 'http://www.lingjiamao.cn'
} else {
	BASE_URL = 'http://www.lingjiamao.cn'
}
// GET请求
function GET(requestHandler, isShowLoading) {
	return request('GET', requestHandler, isShowLoading)
}
// POST请求
function POST(requestHandler, isShowLoading) {
	return request('POST', requestHandler, isShowLoading, requestHandler.companyCode)
}
// PUT请求
function PUT(requestHandler, isShowLoading) {
	return request('PUT', requestHandler, isShowLoading)
}
// DELETE请求
function DELETE(requestHandler, isShowLoading) {
	return request('DELETE', requestHandler, isShowLoading)
}

function getHeaders(token, companyCode) {
	let company = uni.getStorageSync('enterprise')
	return {
		AccessToken: token,
		TenantId: companyCode ? companyCode : company
	}
}
let isLoading = false

function request(method, requestHandler, isShowLoading = true, companyCode) {
	let token = uni.getStorageSync("token")
	let params = requestHandler.params
	let times
	// if (!isLoading) {
	// 	uni.showLoading({
	// 		title: '加载中...'
	// 	})
	// 	isLoading = true
	// }
	return new Promise((resolve, reject) => {
		uni.request({
			url: BASE_URL + requestHandler.url,
			data: params,
			method: method,
			header: {
				'token': token
			},
			success: (res) => {
				uni.hideLoading()
				if (times) {
					clearTimeout(times)
				}
				isShowLoading && uni.hideLoading && uni.hideLoading()
				const result = res.data
				if (result.code === 401) {
					uni.showToast({
						title: '登录失效,请重新登录!',
						icon: 'none',
						duration: 3000
					})
					uni.reLaunch({
						url: '/pages/login/login'
					})
					return
				}
				if (result.code && result.code !== 1) {
					if (res.data.code === 500) {
						uni.showToast({
							title: '服务出错了,请退出登录后重新登录!',
							icon: 'none',
							duration: 3000
						})
						return
					}
					uni.showToast({
						title: result.error || result.message,
						icon: 'none',
						duration: 3000
					})
					reject(result)
				} else {
					resolve(result)
				}
			},
			fail: function(e) {
				uni.hideLoading()
				if (times) {
					clearTimeout(times)
				}
				// 因为hide会让showToast隐藏
				if (!isLoading) {
					uni.showToast({
						icon: 'none',
						title: '网络请求失败',
						duration: 3000
					})
				}

				reject(new Error('Network request failed'))
			}
		})
	})
}
module.exports = {
	get: GET,
	post: POST,
	put: PUT,
	delete: DELETE
}